<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="formVisible = true" v-if="isAdmin">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="课程名" value="1"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok"/>
      </div>
    </div>
    <el-table stripe style="width: 100%"  border fit highlight-current-row ref="tableDataRef" :data="tableData" :key="key">
      <el-table-column v-if="colData[0].istrue" min-width="50" align="center" prop="course_id" label="ID"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="course_img" label="图标">
        <template slot-scope="scope">
          <el-image  style="width: 80px; height: 80px"  :src="scope.row.course_img" fit="fill"></el-image>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[2].istrue" min-width="50" align="center" prop="course_name" label="课程名"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="50" align="center" prop="course_type" label="课程性质">
        <template slot-scope="scope">
          <span v-if="scope.row.course_type==1">视频</span>
          <span v-if="scope.row.course_type==2">音频</span>
          <span v-if="scope.row.course_type==3">文档</span>
          <span v-if="scope.row.course_type==4">图片</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[4].istrue" min-width="50" align="center" prop="course_size" label="课程文件大小">
        <template slot-scope="scope">{{scope.row.course_size| zhDate}}</template>
      </el-table-column>
      <el-table-column v-if="colData[5].istrue" min-width="120" align="center" prop="platter_id" label="套餐归属">
        <template slot-scope="scope">
          <el-select v-show="scope.row.platter_id.length>0" v-model="scope.row.platter_id" placeholder="请选择" multiple disabled>
            <el-option
              v-for="item in scope.row.platterArr"
              :key="item.id"
              :label="item.name"
              :value="item.id.toString()">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[7].istrue" min-width="50" align="center" prop="suitable_grade" label="适配学龄段">
        <template slot-scope="scope">
          <span>{{scope.row.gradeStr}}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[6].istrue" min-width="50" align="center" prop="course_explain" label="说明"></el-table-column>
      <el-table-column v-if="isAdmin" label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="openEdit(scope.row)">编辑</el-button>
            <el-button size="mini" @click="delCourse(scope.row.course_id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
                     layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- 添加弹窗 -->
    <el-dialog title="添加课程" :visible.sync="formVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="40%" @close="addFormclose">
      <el-form :model="addForm"  ref="ruleForm" :rules="rules" class="diolog_adapt" style="width: 600px" >
        <el-form-item label="图标:" label-width="120px" prop="course_img">
          <el-upload
            class="avatar-uploader"
            action
            :auto-upload="false"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-change="courseImgUpload"
          >
            <img v-if="addForm.course_img" :src="addForm.course_img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文件上传:" label-width="120px" prop="course_url">
          <div class="flex felx_align">
            <el-upload class="upload-demo" action="#" id="file" :auto-upload="false" :show-file-list="false" :on-change="courseUpload">
              <el-button size="small" type="primary"><span>文件上传</span></el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="课程名:" label-width="120px" prop="course_name">
          <el-input v-model="addForm.course_name" placeholder="请输入课程名"></el-input>
        </el-form-item>
        <el-form-item label="课程文件性质:" label-width="120px" prop="course_type">
          <el-select v-model="addForm.course_type" placeholder="请选择">
            <el-option
              v-for="item in courseTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适配学龄" label-width="120px" prop="suitable_grade" >
          <el-select v-model="addForm.suitable_grade" multiple placeholder="请选择适配学龄段" class="add_select">
            <el-option
              v-for="item in gradeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐归属:" label-width="120px" prop="platter_id">
          <el-select v-model="addForm.platter_id" multiple placeholder="请选择">
            <el-option
              v-for="item in platterOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id.toString()">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="说明:" label-width="120px" prop="course_explain">
          <el-input v-model="addForm.course_explain" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" size="mini" round @click="editCourse('ruleForm')">确 定
        </el-button>
        <el-button v-else type="primary" @click="addCourse('ruleForm')" size="mini" round>确定</el-button>
      </div>
    </el-dialog>
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>

</template>

<script>
  import objectable from "@/utils/objectable.js";
  import dynamicTable from "@/components/DynamicTable";
  import deleteDialog from "@/components/deleteDialog";
  import tableMini from '@/utils/tableMini.js'
  import {addCourseControl,queryCourseControl,editCourseData,delCourseControl} from "@/api/launcherMade";
  import {ossFile, ossImage} from "@/utils/ossUpload";
  export default {
    mixins: [tableMini],
    components: {dynamicTable, deleteDialog},
    data() {
      return {
        key: 1,
        colData: [], //动态控制table
        checkboxVal: ["ID", "图标", "课程名", "课程文件性质", "课程文件大小", "套餐归属", "说明", "适配学龄段"],
        searchTable: "",
        select: "", //搜索条件
        tableData: [],
        listQuery: {
          startSize: 1,
          pageSize: 10,
          userId: localStorage.getItem("ID"),
          is_charge: 1,
        },
        addForm: {
          course_img: '',
          course_name: '',
          course_type: '',
          course_size: '',
          platter_id: '',
          course_explain: '',
          suitable_grade: '', //适配年龄
          course_url: '',
        },
        formVisible: false,
        rules: {
          course_name: [{required: true, message: '请输入名称', trigger: 'blur'}],
          suitable_grade: [{required: true, message: '请选择适配学龄', trigger: 'blur'}],
          platter_id: [{required: true, message: '请选择套餐归属', trigger: 'blur'}],
          course_type: [{ required: true, message: '请选择课程文件性质', trigger: 'change' }],
          course_url: [{required: true, message: '请上传文件', trigger: 'blur'}],
        },
        editSubjects: false,
        courseTypeOptions: [{label:'视频',value:1},{label: '音频',value: 2}, {label: '文档',value: 3}, {label: '图片', value: 4}],
        platterOptions: [],
        deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
        gradeOptions: [{label: '幼儿', value: 1}, {label: '小学', value: 2}, {label: '初中', value: 3}, {label: '高中', value: 4}],
        isAdmin: true
      }
    },
    created() {
      this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
      this.getCourseTableData()
      if (localStorage.getItem("roleName") != '超级管理员' || localStorage.getItem("roleName") == '管理员') {
        this.isAdmin = false
      }
    },
    methods: {
      Refresh() {
        this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), name: undefined}
        this.getCourseTableData()
      },

      //搜索,1:课程名称
      idnameSearch() {
        if (!this.select) return this.$message.warning("请先选择查询条件");
        this.listQuery.startSize = 1
        this.listQuery.pageSize = 10
        switch (this.select) {
          case '1':
            this.listQuery.course_name = this.searchTable
            this.getCourseTableData();
            break;
        }
      },
      openEdit(row) {
        this.formVisible = true
        this.editSubjects=true
        this.addForm=row
      },
      addCourse(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let addForm = JSON.parse(JSON.stringify(this.addForm))
            addForm.last_ip = sessionStorage.getItem("Ip")
            addForm.userId = localStorage.getItem("ID")
            addForm.is_charge = 1
            addCourseControl(addForm).then(res => {
              if(res.code==200){
                this.$message.success(res.msg)
                this.getCourseTableData()
              }
              this.formVisible = false
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },
      getCourseTableData() {
        queryCourseControl(this.listQuery).then(res => {
          if(res.code==200){
            this.tableData = res.data
            this.total = res.total
            this.platterOptions = res.otherData.platterOptions
          }else{
            this.$message.error(this.res.msg)
          }
        }).catch(err => {
          this.tableData = []
          this.total = 0
        })
      },
      editCourse(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let editForm = JSON.parse(JSON.stringify(this.addForm))
            editForm.last_ip = sessionStorage.getItem("Ip")
            editForm.userId = localStorage.getItem("ID")
            editCourseData(editForm).then(res => {
              this.$message.success(res.msg)
              this.formVisible = false
              this.getCourseTableData()
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },
      delCourse(id) {
        this.deleteDialogs.show = true
        this.deleteDialogs.deleteId = id
      },
      //删除按钮事件
      deleteEvents() {
        let params = {
          userId: localStorage.getItem("ID"),
          last_ip: sessionStorage.getItem("Ip"),
          course_id: this.deleteDialogs.deleteId,
        }
        delCourseControl(params).then(res => {
          if(res.code==200){
            this.$message.success(res.msg)
          }else{
            this.$message.error(res.msg)
          }
          this.getCourseTableData()
        }).catch(err => {
          console.log("请求失败", err)
        })
      },
      //分页
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getTabularData()
      },
      handleCurrentChange(val) {
        this.listQuery.startSize = val
        this.getTabularData()
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      //下拉动态table子组件
      alterCheckbok(key, conte) {
        this.key = key;
        this.colData.filter(i => {
          if (conte.indexOf(i.title) != -1) {
            i.istrue = false;
            this.$nextTick(() => {
              this.$refs.tableDataRef.doLayout();
            });
          } else {
            i.istrue = true;
            this.$nextTick(() => {
              this.$refs.tableDataRef.doLayout();
            });
          }
        });
      },
      //图片上传
      courseImgUpload(res, file) {
        ossImage(res.raw,res.name).then(res => {//图片上传
          this.addForm.course_img = res
        }).catch(err => {
          this.$message.error("图标上传失败")
        })
      },
      //文件上传
      courseUpload(res, file) {
        this.addForm.course_size=res.size
        ossFile(res.raw,res.name).then(res => {//文件上传
          this.addForm.course_url=res
          this.$message.success("上传成功")
        }).catch(err => {
          this.$message.error("文件上传失败")
        })
      },
      //编辑添加表单关闭事件
      addFormclose() {
        this.editSubjects=false
        this.$nextTick(() => {
          this.addForm = this.$options.data().addForm
        })
      },
    }
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
